<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\BehaviorCategory;
use app\common\model\BehaviorRecord;
use app\common\model\InCommonUse;
use app\common\model\UserGroup;
use think\Validate;

/**
 * 用户
 * @package app\api\controller
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobileLogin', 'register', 'resetPwd', 'changeEmail', 'changeMobile', 'third', 'check'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * @ApiTitle    (用户登录)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/7/31 10:27)
     * @ApiSummary  (描述)
     * @ApiBody  (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/login)
     * @ApiParams   (name="account", type="string", required=true, description="账号", sample="")
     * @ApiParams   (name="password", type="string", required=true, description="密码", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn   ({
    "code": 1,
    "msg": "登录成功",
    "time": "1564639763",
    "data": {
    "userinfo": {
    "id": 21,
    "username": "1234561001",
    "nickname": "张三",
    "mobile": "",
    "avatar": "data:image\/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgaGVpZ2h0PSIxMDAiIHdpZHRoPSIxMDAiPjxyZWN0IGZpbGw9InJnYigyMjQsMTYwLDIyOSkiIHg9IjAiIHk9IjAiIHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIj48L3JlY3Q+PHRleHQgeD0iNTAiIHk9IjUwIiBmb250LXNpemU9IjUwIiB0ZXh0LWNvcHk9ImZhc3QiIGZpbGw9IiNmZmZmZmYiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHRleHQtcmlnaHRzPSJhZG1pbiIgYWxpZ25tZW50LWJhc2VsaW5lPSJjZW50cmFsIj7lvKA8L3RleHQ+PC9zdmc+",
    "gender": 1,//1男 2女
    "birthday": null,//生日 date格式
    "score": 0,
    "token": "e960c343-84e3-4c28-9820-9742b0de3009",
    "user_id": 21,
    "createtime": 1564639764,//token创建时间
    "expiretime": 1567231764,//token过期时间
    "expires_in": 2592000//token有效期
    }
    }
    })
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }

        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * @ApiTitle    (注销登录)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2020/1/8)
     * @ApiSummary  (描述)
     * @ApiBody  (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/logout)
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn   ()
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * @ApiTitle    (用户中心)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/7/31 13:54)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/profile)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1582076547",
    "data": {
    "userinfo": {
    "id": 304,
    "username": "18911621396",
    "nickname": "甄子涵",
    "mobile": "18911621396",
    "avatar": "https://mp.uxuj.cn/uploads/20200217/231ac9abaf922880b1339417c0ee46e9.jpg",
    "score": 0,
    "school_id": 3,
    "token": "0bba7525-b595-4226-9066-c288be6a1e4b",
    "user_id": 304,
    "createtime": 1581907765,
    "expiretime": 1584499765,
    "expires_in": 2423217,
    "group_id": 0,
    "group_name": ""
    },
    "school": {
    "id": 36,
    "name": "房山长阳第一小学",
    "province_id": 1,
    "city_id": 2,
    "district_id": 10,
    "address": "长阳镇起步区3号",
    "logo": "https://mp.uxuj.cn/uploads/20191118/b4037c02a840db9dd1a78fa6ca932e1e.jpg",
    "note": null,
    "school_id": 3,
    "admin_id": 0,
    "created_at": 1573873298,
    "classes_count": 16,
    "student_count": 131,
    "teacher_count": 13
    },
    "inCommonUse": [
    {
    "id": 5,
    "user_id": 304,
    "behavior_category_id": 5,
    "created_at": 1582019239,
    "behavior_category_name": "学生测试1",
    "behavior_category_type": 4,
    "behavior_category_type_text": "student"
    },
    {
    "id": 6,
    "user_id": 304,
    "behavior_category_id": 9,
    "created_at": 1582019239,
    "behavior_category_name": "班级测试",
    "behavior_category_type": 1,
    "behavior_category_type_text": "classes"
    }
    ]
    }
    })
     */
    public function profile()
    {
        $data['userinfo'] = $this->auth->getUserinfo();

        if ($data['userinfo']) {
            if (!strstr($data['userinfo']['avatar'], 'http') && strstr($data['userinfo']['avatar'], 'upload')) {
                $data['userinfo']['avatar'] = config('mp.url') . $data['userinfo']['avatar'];
            }
        }

        $rule = [];
        if ($this->auth->school_id) {
            $school_id = $this->auth->school_id;
            $teacher = \app\common\model\Teacher::where('user_id', $this->auth->id)
                ->where('school_id', $school_id)
                ->field('id')
                ->find();
            if ($teacher) {
                $rule['name'] = 'teacher';
                $rule['id'] = $teacher->id;
            } else {
                $student = \app\common\model\Student::where('user_id', $this->auth->id)
                    ->where('school_id', $school_id)
                    ->field('id')
                    ->find();
                if ($student) {
                    $rule['name'] = 'student';
                    $rule['id'] = $student->id;
                }
            }
        } else {
            $teacher = \app\common\model\Teacher::where('user_id', $this->auth->id)->find();
            if ($teacher) {
                $school_id = $teacher->school_id;
                $rule['name'] = 'teacher';
                $rule['id'] = $teacher->id;
            } else {
                $student = \app\common\model\Student::where('user_id', $this->auth->id)->find();
                if ($student) {
                    $classes = \app\common\model\Classes::where('id', $student->class_id)->find();
                    if ($classes) {
                        $school_id = $classes->school_id;
                        $rule['name'] = 'student';
                        $rule['id'] = $student->id;
                    }
                }
            }
        }

        $data['userinfo']['score'] = 0;
        $school = [];
        if (isset($school_id)) {
            $school = \app\common\model\School::where('id', $school_id)
                ->withCount(['classes', 'student', 'teacher'])
                ->find();

            if (!strstr($school->logo, 'http') && strstr($school->logo, '/uploads')) {
                $school->logo = config('mp.url') . $school->logo;
            }

            if ($rule) {
                $school['role_id'] = $rule['id'];
                $school['role_name'] = $rule['name'];

                if ($rule['name'] == 'teacher') {
                    $classes = \app\common\model\Classes::where('headmaster', $rule['id'])->find();
                    if ($classes) {
                        $data['userinfo']['score'] = BehaviorRecord::alias('record')
                            ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.record_id = record.id')
                            ->where('record.school_id', $classes->school_id)
                            ->whereIn('detail.behavior_category_type', [BehaviorCategory::CLASSES,BehaviorCategory::DORM_STUDENT])
                            ->where('detail.class_id', $classes->id)
                            ->sum('detail.score');
                    }
                }
            }
        }
        $data['school'] = $school;

        $data['inCommonUse'] = InCommonUse::alias('a')
            ->join('__BEHAVIOR_CATEGORY__ category', 'category.id = a.behavior_category_id')
            ->where('a.user_id', $this->auth->id)
            ->where('category.status', BehaviorCategory::DISPLAY)
            ->field('a.*,category.name behavior_category_name,category.type behavior_category_type,category.image behavior_category_image')
            ->order('a.id', 'asc')
            ->select();

        if ($data['inCommonUse']) {
            foreach ($data['inCommonUse'] as $key => $datum) {
                switch ($datum['behavior_category_type']) {
                    case BehaviorCategory::CLASSES :
                        $data['inCommonUse'][$key]['behavior_category_type_text'] = 'classes';
                        break;
                    case BehaviorCategory::DORM :
                    case BehaviorCategory::DORM_STUDENT :
                        $data['inCommonUse'][$key]['behavior_category_type_text'] = 'dorm';
                        break;
                    case BehaviorCategory::STUDENT :
                        $data['inCommonUse'][$key]['behavior_category_type_text'] = 'student';
                        break;
                }
            }
        }

        $this->success('', $data);
    }

    /**
     * @ApiTitle    (修改用户个人信息)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/editProfile)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="username", type="string", required=false, description="用户名", sample="")
     * @ApiParams   (name="nickname", type="string", required=false, description="昵称", sample="")
     * @ApiParams   (name="birthday", type="string", required=false, description="生日", sample="")
     * @ApiParams   (name="avatar", type="string", required=false, description="头像地址", sample="")
     * @ApiParams   (name="bio", type="string", required=false, description="个人简介", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1564640159",
    "data": null
    })
     */
    public function editProfile()
    {
        $username = $this->request->request('username');
        $nickname = $this->request->request('nickname');
        $bio = $this->request->request('bio');
        $avatar = $this->request->request('avatar', '', 'trim,strip_tags,htmlspecialchars');

        $ret = $this->post('/api/user/editProfile', compact('username', 'nickname', 'bio', 'avatar'));

        if ($ret['code']) {
            $this->success('修改成功');
        }

        $this->error('修改失败');
    }

    /**
     * @ApiTitle    (修改学校)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2020/3/5 10:27)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/editSchool)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="school_id", type="int", required=true, description="学校 id", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1564640159",
    "data": null
    })
     */
    public function editSchool()
    {
        $school_id = $this->request->request('school_id');

        $ret = $this->post('/api/user/editSchool', compact('school_id'));

        $this->result($ret['msg'], $ret['data'], $ret['code']);
    }

    /**
     * @ApiTitle    (权限列表)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/8/9 10:37)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/ruleList)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function ruleList()
    {
        $data = $this->auth->getRuleList();

        $this->success('', $data);
    }

    /**
     * @ApiTitle    (检测是否是否有对应权限)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/8/13 15:43)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/check)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="path", type="string", required=true, description="控制器/方法", sample="")
     * @ApiParams   (name="module", type="string", required=true, description="模块 默认为当前模块", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function check()
    {
        $path = $this->request->request('path');
        $module = $this->request->request('module', null);

        $result = $this->auth->check($path, $module);

        $this->success('', $result);
    }

    /**
     * @ApiTitle    (修改密码)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/changePwd)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="mobile", type="string", required=false, description="手机号", sample="")
     * @ApiParams   (name="captcha", type="string", required=false, description="验证码", sample="")
     * @ApiParams   (name="password", type="string", required=false, description="新密码", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1564640159",
    "data": null
    })
     */
    public function changePwd()
    {
        $mobile = $this->request->request('mobile');
        $password = $this->request->request('password');
        $captcha = $this->request->request('captcha');

        $ret = $this->post('/api/user/changePwd', compact('mobile', 'password', 'captcha'));

        if ($ret['code']) {
            $this->success($ret['msg']);
        }

        $this->error($ret['msg']);
    }

    /**
     * @ApiTitle    (绑定手机号)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/7/31 10:49)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/bindMobile)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号", sample="")
     * @ApiParams   (name="captcha", type="string", required=true, description="验证码", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "绑定成功",
    "time": "1564542858",
    "data": null
    })
     */
    public function bindMobile()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');

        if (!$mobile || !$captcha)
            $this->error(__('Invalid parameters'));

        if (!Validate::regex($mobile, "^1\d{10}$"))
            $this->error(__('Mobile is incorrect'));

        $ret = $this->post('/api/user/bindMobile', compact('mobile', 'captcha'));

        if ($ret['code']) {
            $this->success($ret['msg']);
        }

        $this->error($ret['msg']);
    }

    /**
     * @ApiTitle    (手机号登录)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/7/31 10:32)
     * @ApiSummary  (描述)
     * @ApiBody  (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/mobileLogin)
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号", sample="")
     * @ApiParams   (name="captcha", type="string", required=true, description="验证码", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function mobileLogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }

        $ret = $this->post('/api/user/mobileLogin', compact('mobile', 'captcha'));

        if ($ret['code']) {
            $this->success($ret['msg'], $ret['data']);
        }

        $this->error($ret['msg']);
    }

    /**
     * @ApiTitle    (重置密码)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2020/1/8 10:32)
     * @ApiSummary  (描述)
     * @ApiBody  (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/resetPwd)
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号", sample="")
     * @ApiParams   (name="password", type="string", required=true, description="密码", sample="")
     * @ApiParams   (name="captcha", type="string", required=true, description="验证码", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function resetPwd()
    {
        $mobile = $this->request->request("mobile");
        $password = $this->request->request("password");
        $captcha = $this->request->request("captcha");
        if (!$password || !$captcha) {
            $this->error(__('Invalid parameters'));
        }

        $ret = $this->post('/api/user/resetPwd', compact('mobile', 'password', 'captcha'));

        if ($ret['code']) {
            $this->success($ret['msg'], $ret['data']);
        }

        $this->error($ret['msg']);
    }

    /**
     * @ApiTitle    (设置常用功能)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/2/18)
     * @ApiSummary  (描述)
     * @ApiBody     ()
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/setInCommonUse)
     * @ApiParams   (name="ids", type="string", required=true, description="行为分类 ids 英文,连接的字符串", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1582019237",
    "data": null
    })
     */
    public function setInCommonUse()
    {
        $behavior_category_ids = $this->request->post('ids');

        if (!is_array($behavior_category_ids)) {
            $behavior_category_ids = explode(',', $behavior_category_ids);
        }

        // 前端传过来的 ids 可能有错误的 筛查一下
        $behavior_categories = BehaviorCategory::whereIn('id', $behavior_category_ids)->where('status', BehaviorCategory::DISPLAY)->field('id')->select();
        $behavior_category_ids = array_column($behavior_categories, 'id');

        $user_id = $this->auth->id;

        InCommonUse::where('user_id', $user_id)->delete();

        $insert_data = [];
        foreach ($behavior_category_ids as $key => $datum) {
            $insert_data[] = [
                'user_id' => $user_id,
                'behavior_category_id' => $datum,
            ];
        }

        $inCommonUse = new InCommonUse();
        $flag = $inCommonUse->saveAll($insert_data);

        if ($flag) {
            $this->success('');
        } else {
            $this->error('');
        }
    }

}
